﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace HttpTest
{
    public partial class Form1 : Form
    {
        private readonly String hashKey = "q@#&^%[$";
        public Form1()
        {
            InitializeComponent();

            string userName1 = ConfigurationManager.AppSettings["userName"].ToString();
            string userPwd1 = ConfigurationManager.AppSettings["userPwd"].ToString();
            txtLogin.Text = DecryptString(userName1, hashKey); txtPassword.Text = DecryptString(userPwd1, hashKey);
            if (string.IsNullOrEmpty(txtLogin.Text) && string.IsNullOrEmpty(txtPassword.Text))
            {
                txtLogin.Text = "13168607788";
                txtPassword.Text = "zwl2062436aa";
            }
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string Account = txtLogin.Text;
            string PassWord = txtPassword.Text;
            if (!string.IsNullOrEmpty(Account) && !string.IsNullOrEmpty(PassWord))
            {
                string aq_0 = "您需要安装安全控件，才可使用安全登录。";
                string aq_1 = "您还未安装密码安全控件，安装后即可输入密码。";
                string AbsoluteUri = string.Empty;
                string LoginUrl = "https://account.xiaomi.com/pass/serviceLoginAuth";
                string PostData = "passToken=&user=" + Account + "&pwd=" + PassWord + "&callback=https%3A%2F%2Faccount.xiaomi.com&sid=passport&hidden=";
                AbsoluteUri = HttpHelper.PostData(LoginUrl, PostData);
                //taobao "https://login.taobao.com/", "TPL_username=" + Account +
                //"&TPL_password=" + PassWord + "&actionForStable=enable_post_user_action&action=Authenticator&event_submit_do_login=anything", ref AbsoluteUri);
                if (!string.IsNullOrEmpty(AbsoluteUri))
                {
                    if (Regex.IsMatch(AbsoluteUri, "safe/check_ip.do"))
                    {
                        MessageBox.Show("请在淘宝页面 [账号管理] 页面关闭 [登录保护] 功能或设置不进行二次验证地域.");
                    }
                    else if (AbsoluteUri.IndexOf(aq_0) == -1 && AbsoluteUri.IndexOf(aq_1) == -1)
                    {
                        ////MessageBox.Show("登陆成功！");
                        // 写入参数设置
                        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        configuration.AppSettings.Settings["userName"].Value = EncryptString(txtLogin.Text, hashKey);
                        configuration.AppSettings.Settings["userPwd"].Value = EncryptString(txtPassword.Text, hashKey);
                        configuration.Save();
                        // 重新读取参数
                        ConfigurationManager.RefreshSection("appSettings");

                        UserInfo f = (UserInfo)this.Owner;
                        f.Text = "登陆成功";
                        f.AppendText(f.Text);
                        this.DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        if (AbsoluteUri.IndexOf("您输入的密码和账户名不匹配") > 0)
                        {
                            MessageBox.Show("您输入的密码和账户名不匹配，请重新输入。");
                        }
                        else
                        {
                            //返回的 HTML 代码中包含 以上两句话说明登陆失败，一般情况下需要淘宝用户手动登陆一下淘宝，然后再使用以上代码自动登陆就可以正常登陆了。
                            MessageBox.Show("登陆失败！");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("登陆失败，未知原因！");
                }
            }
            else
            {
                MessageBox.Show("用户名和密码不能为空！");
            }
        }

        #region "3des加密字符串".
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptString(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        #endregion

        #region "3des解密字符串"
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptString(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

        #endregion
    }
}
